/**
 * createby : JinxLbj
 * date : 2018/8/10
 * desc : 自定义线程类
 **/

package com.example.demo.common.thread;

import com.example.demo.common.service.ProcessService;
import com.example.demo.common.service.impl.ProcessServiceImpl;
import com.example.demo.common.utils.SFTPChannel;
import com.example.demo.netty.service.NettyService;
import com.example.demo.netty.service.impl.NettyServiceImpl;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ProcessThread extends Thread {

    private ProcessService processServiceImpl = new ProcessServiceImpl();

    private NettyService nettyServiceImpl = new NettyServiceImpl();

    private SFTPChannel sftpChannel = new SFTPChannel();

    private String command;

    private String projectName;

    public ProcessThread(String command, String projectName, String runCommand) {
        this.command = command;
        this.projectName = projectName;
    }

    @Override
    public void run() {
        Process process = null;
        try {
            System.out.println(">> 子线程开始执行");
            process = Runtime.getRuntime().exec(new String[]{"sh", "-c", command});
            nettyServiceImpl.sendMessageToEveryone(projectName, command);
            //放入进程组
            processServiceImpl.putProcess(process, projectName, command);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null) {
                nettyServiceImpl.sendMessageToEveryone(projectName, new String(line.getBytes(), "GBK") + "\n");
                System.out.println(new String(line.getBytes(), "GBK"));
            }
            br.close();
            System.out.println(process.waitFor());
        } catch (IOException e) {
            System.out.println(">> 线程异常");
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            processServiceImpl.killProcessError(projectName);
            if (process != null) {
                process.destroy();
            }
            System.out.println(">> 线程销毁");
        }

    }


}
